{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h1>Perform Federated Learning at PyGrid Platform </h1>\n",
    "In this notebook, we will train a model using federated approach.\n",
    "\n",
    "**NOTE:** At the time of running this notebook, we were running the PyGrid components in background mode.  \n",
    "\n",
    "**NOTE:**\n",
    "Components:\n",
    " - PyGrid Network\n",
    " - 3 PyGrid Node\n",
    "\n",
    "This notebook was made based on <a href=\"https://github.com/OpenMined/PySyft/blob/dev/examples/tutorials/Part%2010%20-%20Federated%20Learning%20with%20Secure%20Aggregation.ipynb\">Part 10: Federated Learning with Encrypted Gradient Aggregation</a> tutorial"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import syft as sy\n",
    "from syft.grid.public_grid import PublicGridNetwork\n",
    "import torch as th\n",
    "import torch.nn as nn\n",
    "import torch.optim as optim\n",
    "import torch.nn.functional as F"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "hook = sy.TorchHook(th)\n",
    "class Net(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(Net, self).__init__()\n",
    "        self.conv1 = nn.Conv2d(1, 20, 5, 1)\n",
    "        self.conv2 = nn.Conv2d(20, 50, 5, 1)\n",
    "        self.fc1 = nn.Linear(4*4*50, 500)\n",
    "        self.fc2 = nn.Linear(500, 10)\n",
    "\n",
    "    def forward(self, x):\n",
    "        x = F.relu(self.conv1(x))\n",
    "        x = F.max_pool2d(x, 2, 2)\n",
    "        x = F.relu(self.conv2(x))\n",
    "        x = F.max_pool2d(x, 2, 2)\n",
    "        x = x.view(-1, 4*4*50)\n",
    "        x = F.relu(self.fc1(x))\n",
    "        x = self.fc2(x)\n",
    "        return F.log_softmax(x, dim=1)\n",
    "\n",
    "\n",
    "device = th.device(\"cuda:0\" if th.cuda.is_available() else \"cpu\")\n",
    "\n",
    "if(th.cuda.is_available()):\n",
    "    th.set_default_tensor_type(th.cuda.FloatTensor)\n",
    "    \n",
    "model = Net()\n",
    "model.to(device)\n",
    "optimizer = optim.SGD(model.parameters(), lr=0.01)\n",
    "criterion = nn.CrossEntropyLoss()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3>Copy the PyGrid Network IP from Part-1 and paste it in the place of grid address</h3>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "GRID_ADDRESS = 'xxxxxxxxxxx'\n",
    "\n",
    "my_grid = PublicGridNetwork(hook,\"http://\" + GRID_ADDRESS)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = my_grid.search(\"#X\", \"#mnist\", \"#dataset\")\n",
    "target = my_grid.search(\"#Y\", \"#mnist\", \"#dataset\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "target"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = list(data.values())\n",
    "target = list(target.values())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def epoch_total_size(data):\n",
    "    total = 0\n",
    "    for i in range(len(data)):\n",
    "        for j in range(len(data[i])):\n",
    "            total += data[i][j].shape[0]\n",
    "            \n",
    "    return total"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "N_EPOCS = 3\n",
    "SAVE_MODEL = True\n",
    "SAVE_MODEL_PATH = './models'\n",
    "\n",
    "def train(epoch):\n",
    "    model.train()\n",
    "    epoch_total = epoch_total_size(data)\n",
    "    current_epoch_size = 0\n",
    "    for i in range(len(data)):\n",
    "        for j in range(len(data[i])):\n",
    "            current_epoch_size += len(data[i][j])\n",
    "            worker = data[i][j].location\n",
    "            model.send(worker)\n",
    "            optimizer.zero_grad()\n",
    "            pred = model(data[i][j])\n",
    "            loss = criterion(pred, target[i][j])\n",
    "            loss.backward()\n",
    "            optimizer.step()\n",
    "            model.get()\n",
    "            loss = loss.get()\n",
    "            print('Train Epoch: {} | With {} data |: [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n",
    "                      epoch, worker.id, current_epoch_size, epoch_total,\n",
    "                            100. *  current_epoch_size / epoch_total, loss.item()))\n",
    "                    \n",
    "for epoch in range(N_EPOCS):\n",
    "    train(epoch)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6-final"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}